package com.psychologyCommunity.Community.Contoller;

import com.psychologyCommunity.Community.entity.DiscussPost;
import com.psychologyCommunity.Community.entity.Page;
import com.psychologyCommunity.Community.service.ElasticsearchService;
import com.psychologyCommunity.Community.service.LikeService;
import com.psychologyCommunity.Community.service.UserService;
import com.psychologyCommunity.Community.util.CommunityConstance;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController implements CommunityConstance {
    @Autowired
    private ElasticsearchService elasticsearchService;
    //要展示出 帖子的作者 和帖子的点赞的次数，拿到数据要注入UserService LikeService
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    //用 search?keyword=xxxx来传keyword
    @RequestMapping(path = "/search",method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model){
        //搜索帖子--封装的page.getCurrent()是从1 开始 但是 search方法中是要要求按0开始
        org.springframework.data.domain.Page<DiscussPost> searchResult=
        elasticsearchService.searchDiscuss(keyword,page.getCurrent()-1,page.getLimit());
        //帖子里面拿到的只是discussPost实体，还有帖子的作者 和帖子的点赞的次数 需要聚合一下
        //聚合数据
        List<Map<String,Object>> discussPosts=new ArrayList<>();
        if(searchResult!=null){
            for (DiscussPost post :searchResult) {
                Map<String ,Object> map=new HashMap<>();
                //帖子
                map.put("post",post);
                //作者
                map.put("user",userService.findUserById(post.getUserid()));
                //点赞数量
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST,post.getId()));
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("keyword",keyword);
        //分页信息
        page.setPath("/search?keyword="+keyword);
        page.setRows(searchResult ==null ?0: (int) searchResult.getTotalElements());
        return "/site/search";
    }

}
